'''

@author: wyndem
@Emil:   wyndem@qq.com
@FileName: thriftservice.py
@Time: 2019/3/13 9:51
@Software: PyCharm
@Description: 

'''
import threading

from thrift.protocol import TBinaryProtocol
from thrift.server import TServer
from thrift.transport import TSocket, TTransport

from novel.config.rules import ONLINE_CHAPTER_RULES
from novel.dao import charpterdao
from novel.thrift_rpc import ChapterService
from novel.thrift_rpc.ttypes import Chapter
from novel.utils.tool import TOOL


def preloading(cid,method):
    id=int(cid)+1
    charpter = charpterdao.findById(id)
    if charpter == None:
        return
    if (charpter[4]==None or charpter[4]==""):
        titile, context = method(charpter[-1])
        charpterdao.updata({
            "title": charpter[3],
            "text": context,
            "source": charpter[-1]
        })


class CalculatorHandler(ChapterService.Iface):


    def getChapter(self, cid):
        c = Chapter()
        charpter = charpterdao.findById(cid)
        if charpter == None:
            return c
        if (charpter[4]==None or charpter[4]==""):
            method = ONLINE_CHAPTER_RULES.get(TOOL.get_host_url(charpter[-1]))

            t1 = threading.Thread(target=preloading, args=(cid,method,))
            t1.start()
            titile, c.context = method(charpter[-1])
            c.cid = cid
            c.nid = charpter[1]
            c.source = charpter[-1]
            # (item['id'], item['no'], item['title'], item['text'], item['source']
            charpterdao.updata({
                "title": charpter[3],
                "text": c.context,
                "source": c.source
            })

        return c




if __name__ == '__main__':
    handler = CalculatorHandler()
    processor = ChapterService.Processor(handler)
    transport = TSocket.TServerSocket(host='127.0.0.1', port=9090)
    tfactory = TTransport.TBufferedTransportFactory()
    pfactory = TBinaryProtocol.TBinaryProtocolFactory()
    server = TServer.TSimpleServer(processor, transport, tfactory, pfactory)
    TOOL.logging().info("服务器启动成功")
    server.serve()
